package com.studentmanagement.utils;

import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    
    static {
        try {
            // 优先使用mybatis-config.xml配置
            String resource = "mybatis-config.xml";
            InputStream inputStream = null;
            
            try {
                // 先尝试使用外部配置
                File externalConfig = new File("config/mybatis-config.xml");
                if (externalConfig.exists()) {
                    inputStream = new FileInputStream(externalConfig);
                    System.out.println("使用外部MyBatis配置文件: " + externalConfig.getAbsolutePath());
                }
            } catch (Exception e) {
                // 忽略异常，继续尝试其他方式
            }
            
            if (inputStream == null) {
                // 如果外部配置不存在，尝试从classpath加载
                try {
                    inputStream = Resources.getResourceAsStream(resource);
                    System.out.println("使用内部MyBatis配置文件");
                } catch (IOException e) {
                    // 配置文件加载失败，将采用编程方式配置MyBatis
                    System.out.println("未找到MyBatis配置文件，使用编程方式配置");
                    inputStream = null;
                }
            }
            
            if (inputStream != null) {
                // 如果找到配置文件，使用配置文件创建SqlSessionFactory
                // 使用DatabaseConfig中的属性覆盖配置文件中的同名属性
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, DatabaseConfig.getProperties());
                inputStream.close();
            } else {
                // 如果没有找到配置文件，编程方式配置MyBatis
                PooledDataSourceFactory dataSourceFactory = new PooledDataSourceFactory();
                Properties dataSourceProperties = new Properties();
                dataSourceProperties.setProperty("driver", DatabaseConfig.getDriver());
                dataSourceProperties.setProperty("url", DatabaseConfig.getUrl());
                dataSourceProperties.setProperty("username", DatabaseConfig.getUsername());
                dataSourceProperties.setProperty("password", DatabaseConfig.getPassword());
                dataSourceFactory.setProperties(dataSourceProperties);
                
                DataSource dataSource = dataSourceFactory.getDataSource();
                Environment environment = new Environment("development", new JdbcTransactionFactory(), dataSource);
                
                Configuration configuration = new Configuration(environment);
                configuration.setMapUnderscoreToCamelCase(true);
                configuration.setLazyLoadingEnabled(true);
                configuration.setAggressiveLazyLoading(false);
                configuration.setCacheEnabled(true);
                
                // 添加Mapper类和XML映射文件
                // 这里需要根据实际情况添加您的Mapper类
                // 例如：configuration.addMapper(com.studentmanagement.dao.UserMapper.class);
                
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error initializing SqlSessionFactory: " + e.getMessage());
        }
    }
    
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
    
    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }
    
    public static void closeSession(SqlSession session) {
        if (session != null) {
            session.close();
        }
    }
} 